/*
 * Copyright (C) 2006 Johan Maasing johan at zoom.nu Licensed under the Apache
 * License, Version 2.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law
 * or agreed to in writing, software distributed under the License is
 * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package nu.zoom.catonine.swing.tail;

import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;

import javax.swing.Icon;

import nu.zoom.swing.action.AbstractTypedAction;
import nu.zoom.ui.Resources;
import nu.zoom.ui.Resources.ResourceNotFoundException;

/**
 * Action to control the "follow" status of the tail pane.
 * 
 * @author "Johan Maasing" &lt;johan@zoom.nu&gt;
 * 
 */
class TailControlAction extends AbstractTypedAction {

	private static final long serialVersionUID = 1L;
	private TailPane tailer;
	private final String startFollowText;
	private final String stopFollowText;
	private final Icon startFollowIcon;
	private final Icon stopFollowIcon;

	public TailControlAction(final TailPane tailer, final Resources localizedResources)
			throws ResourceNotFoundException {
		this.tailer = tailer;
		startFollowText = localizedResources.getMessage("nu.zoom.catonine.tail.startfollow");
		startFollowIcon = localizedResources.getIcon("nu.zoom.catonine.tail.startfollow.icon");
		stopFollowText = localizedResources.getMessage("nu.zoom.catonine.tail.stopfollow");
		stopFollowIcon = localizedResources.getIcon("nu.zoom.catonine.tail.stopfollow.icon");
		setName(stopFollowText);
		setIcon(stopFollowIcon);
		setToolTip(localizedResources.getMessage("nu.zoom.catonine.tail.tt"));
		setMnemonicKey(KeyEvent.VK_F);
		setAcceleratorKey(KeyEvent.VK_F, InputEvent.SHIFT_DOWN_MASK);
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		final boolean newStatus = !tailer.isFollow();
		tailer.setFollow(newStatus);
	}

	void setActive() {
		setName(stopFollowText);
		setIcon(stopFollowIcon);
	}

	void setInactive() {
		setName(startFollowText);
		setIcon(startFollowIcon);
	}

	public void tailerIdle() {
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				setActive();
			}
		});
	}

	public void tailerStopped() {
		EventQueue.invokeLater(new Runnable() {

			@Override
			public void run() {
				setInactive();
			}
		});
	}
}
